<?php
/**
 * 用户模型
 * @author cjli
 *
 */
class UserModel extends Model
{
	
	/**
	 * 帐户类型
	 */
	static $processType = array(
		'0' => '_PROCESS_RECHARGE_',//充值
		'1' => '_PROCESS_DEPOSIT_',//提现
	);
	/**
	 * 帐户状态
	 */
	static $accountStatus = array(
		'0' => '_ACCOUNT_UNCONFIRMED_',//未确认
		'1' => '_ACCOUNT_COMPLETED_', //已完成
		'2' => '_ACCOUNT_CANCEL_', //取消
 	);
	
	/* 帐号变动类型 */
	const ACT_SAVING = 0;     // 帐户冲值
	const ACT_DRAWING = 1;     // 帐户提款
	const ACT_ADJUSTING = 2;   // 调节帐户
	const ACT_REFUND = 3;			//订单退款
	const ACT_PAY = 4;				//订单支付
	const ACT_SHARING = 5;    //订单分成
	const ACT_SHAIDAN = 6;    //晒单分成
	const ACT_OTHER = 99;     // 其他类型
	
	//会员等级列表
	public static function get_rank_list()
	{
		$rankList = array();
		if(S('user_rank_list')){
			$rankList = S('user_rank_list');
		}else{
			$rankdb = D('user_rank');
			$result = $rankdb->select();
			if($result){
				foreach ($result as $rank){
					$rankList[$rank['id']] = $rank; //ID为数组下标
				}
			}
			S('user_rank_list', $rankList);
		}
		return $rankList;
	}

	//获取等级折折扣率
	public static function get_rank_discount($rank_id)
	{
		$rankdb = D('user_rank');
		$discount = $rankdb->where(array('id' => $rank_id))->getField('discount');
		$discount = $discount/100;
		return $discount;
	}
	
	/**
	 * 更新会员等级
	 * @param int $user_id 用户ID号
	 * @param int $rank_point 用户等级积分
	 */
	public static function update_user_rank($user_id, $rank_point)
	{   
	    return ; //暂停更新 20150701
		if(intval($uid)==0)
			return ;
		$rankId = 1;
		$rank_point = intval($rank_point);
		$rankList = self::get_rank_list();
		foreach ($rankList as $id => $rank){
			if($rank_point >= $rank['min_point'] && $rank_point < $rank['max_point']){
				$rankId = $id;break;
			}
		}
		$user_db = D('users');
		$user_db->where('id = '.$user_id)->save(array('rank_id' => $rankId));
	}
	
	/**
	 * 获取用户信息
	 * @param int $user_id 用户ID号
	 * @return Array
	 */
	public static function get_user_info($user_id)
	{
		$user_db = D('users');
		$userInfo = $user_db->find(intval($user_id));
		$userInfo['data'] = (isset($userInfo['data']) && $userInfo['data']) ? unserialize($userInfo['data']) : array();
		return $userInfo;
	}
	
	/**
	 * 通过用户名获取用户信息
	 * @param string $username 用户名
	 */
	public static function get_user_info_by_other($post)
	{
		$set = array(
			'username' => isset($post['username']) ? $post['username'] : null,
			'email' => isset($post['email']) ? $post['email'] : null,
		);
		foreach ($set as $key => $val){
    	if(is_null($val)){
    		unset($set[$key]);
    	}
    }
    if(empty($set)) return false;
		$user_db = D('users');
		$user_id = $user_db->where($set)->getField('id');
		if($user_id){
			$userInfo = self::get_user_info($user_id);
		}
		return isset($userInfo) ? $userInfo : false;
	}
	
	/**
   * 产生用户散列密码
   * @param string $string 密码明文
   * @param string $rand_salt 随机加密码 
   * @return array 散列密码
   */
	public static function generate_password($string, $rand_salt = null)
	{
		$md5password = md5($string);
		if(empty($rand_salt)){
			$rand_salt = rand(1, 9999);
		}
		$newpassword = md5($md5password . $rand_salt);
		return array($newpassword, $rand_salt);
	}

	
	/**
   * 验证用户名密码
   * @param string $username 用户名或者邮箱
   * @param string $password 密码
   * @return int 用户ID
   */
  public static function validate_user($username, $password, $partner=0)
  {
  	$user_db = D('users');
    $username = trim($username);
    $where = array(
    	'is_partner' => $partner, 
    	);
	$username_where['username']  = $username;
	$username_where['email']  = $username;
	$username_where['_logic'] = 'or';

	$where['_complex'] = $username_where;

    $userInfo = $user_db->field('id,password,rand_salt')->where($where)->find();
    if(!$userInfo){
    	return 0;
    }
    list($newpassword, $rand_salt) = self::generate_password($password, $userInfo['rand_salt']);
    if($newpassword != $userInfo['password']){
    	return 0;
    }else{
    	return $userInfo['id'];
    }
  }
  
  /**
   * 新建用户
   * @param array $post 表单数组
   */
  public static function insert_user($post)
  {
  	global $language_id;
  	if (isset($post['username']) && '' == $post['username']) {
      return false;
    }
    list($set['password'], $set['rand_salt']) = self::generate_password($post['password']);
    
    $set['username'] = trim($post['username']);
    
    //注册送100活动
    isset($post['user_money']) ? $set['user_money'] = $post['user_money'] : 0;
    
    
    isset($post['first_name']) ? $set['first_name'] = trim($post['first_name']) : null;
    isset($post['last_name']) ? $set['last_name'] = trim($post['last_name']) : null;
    isset($post['user_photo']) ? $set['user_photo'] = $post['user_photo'] : '';
    isset($post['nickname']) ? $set['nickname'] = trim($post['nickname']) : '';
    isset($post['gender']) ? $set['gender'] = $post['gender'] : 0;
    isset($post['birthday']) ? $set['birthday'] = $post['birthday'] : '';
    isset($post['email']) ? $set['email'] = trim($post['email']) : '';
    isset($post['data']) ? ($set['data'] = is_array($post['data']) ? serialize($post['data']) : $post['data']) : '';
    $set['reg_time'] = time();
    $set['login_time'] = time();
    $set['login_ip'] = get_client_ip();
    $set['language_id'] = $language_id;
    $set['is_validate_email'] = 0;
    $set['is_designer'] = isset($post['is_designer']) ? 1 : 0;
    $user_db = D('users');
    if($set['user_money']<=100){
    $last_id = $user_db->add($set);
    }
    return $last_id;
  }
//新用户注册
 /* public static function new_user_register(){
	 global $language_id;
	$bounus_type_db = D("bonus_type");	
	$data['type_name'] = ' new user register';
	$data['type_money'] =10;
	$data['send_start_date'] =time();
	$last_id = $bounus_type_db->add($data);
	if($last_id){
		$user_bonus = D("user_bonus");
		$set['user_id'] =$last_id['user_id'];
		$set['bonus_sn'] = 0;
		$set['used_time'] = $last_id['send_start_date'];
		$set['order_id'] =$last_id['order_id']; 
		$data['emailed'] = 1;
		$user_bonus = $user_bonus->add($data);
		return $user_bonus;
  }*/
  
	/**
   * 修改用户
   * @param int $user_id 用户ID
   * @param array $post 表单数组
   * @return int
   */
  public static function update_user($user_id, $post)
  {
    if (isset($post['username'])) {
      unset($post['username']);
    }
    $userInfo = self::get_user_info($user_id);
    if (isset($post['password'])) {
      list($post['password'], $rand_salt) = self::generate_password($post['password'], $userInfo['rand_salt']);
    }
    $set = $post;
    isset($post['first_name']) ? $set['first_name'] = $post['first_name'] : null;
    isset($post['last_name']) ? $set['last_name'] = $post['last_name'] : null;
    isset($post['gender']) ? $set['gender'] = $post['gender'] : 0;
    isset($post['nickname']) ? $set['nickname'] = $post['nickname'] : '';
    isset($post['user_photo']) ? $set['user_photo'] = $post['user_photo'] : '';
    isset($post['birthday']) ? $set['birthday'] = $post['birthday'] : '';
    isset($post['email']) ? $set['email'] = $post['email'] : '';
    isset($post['phone']) ? $set['phone'] = $post['phone'] : '';
    isset($post['mobile']) ? $set['mobile'] = $post['mobile'] : '';
    isset($post['data']) ? ( $set['data'] = is_array($post['data']) ?  serialize($post['data']) : $post['data']) : '';
//    isset($post['rid']) ? $set['rid'] = $post['rid'] : 1;
    $set['login_time'] = time();
    $set['login_ip'] = get_client_ip();
    $user_db = D('users');
    $affected = $user_db->where('id='.$user_id)->save($set);
//    echo $user_db->getLastSql();exit;
    return (boolean)$affected;
  }
	
	/**
   * 检查用户是否已登录
   * @return boolean
   */
  public static function logged()
  {
    global $user;
    return (isset($user['id']) && $user['id']) ? true : false;
  }
  
  /**
   * 登录出
   */
  public static function logout()
  {
  	S('user_info', NULL);
  	session('user_id', NULL);
  	//CartModel::clearCart();
  	unset($_SESSION['cart']);
  }
  
	/**
   * 设置用户登录
   * @param int $user_id 用户ID
   */
  public static function setLogin($user_id)
  {
  	global $user;
  	$user_db = M('Users');
		$sql = "UPDATE __TABLE__ SET `login_count`=(`login_count`+1),`login_ip`='".get_client_ip()."',`login_time`=".time()." WHERE ( `id` = ".$user_id." )";
		$user_db->query($sql);
  }
  
  /**
   * 检验用户名唯一性
   * @param string $username 用户名
   */
  public static function validate_username_only($username)
  {
  	$user_db = D('Users');
  	$count = $user_db->where(array('username' => $username))->count();
  	return (boolean) $count;
  }
  
	/**
   * 检验邮箱唯一性
   * @param string $email 邮箱
   */
  public static function validate_email_only($email, $user_id = 0)
  {
  	$user_db = D('Users');
  	$where['email'] = $email;
  	if($user_id){
  		$where['id'] = array('neq', $user_id);
  	}
  	$count = $user_db->where($where)->count();
  	return (boolean) $count;
  }
  
	/**
	 * 获取用户送货地址列表
	 * @param int $user_id 用户ID号
	 * @return Array
	 */
	public static function get_address_list($user_id, $post = array())
	{
		if(!$user_id)return false;
		$address_db = D('user_address');
		$where = array(
            'user_id' => $user_id,
			);
	    if($post['start_time'] && $post['end_time']){
	        $where['start_time'] =  array(array('gt', strtotime($post['start_time'])), array('lt', strtotime($post['end_time'])), 'AND');
	    }elseif($post['start_time']){
	        $where['start_time'] = array('gt', strtotime($post['start_time']));
	    }elseif($post['end_time']){
	        $where['start_time'] = array('lt', strtotime($post['end_time']));
	    }

	    $address_db->where($where);
		//排序
		if (isset($post['orderby']) && $post['orderby']) {
		  $address_db->order($post['orderby']);
		} else {
		  $address_db->order('`default` DESC');
		}

		$addressList = $address_db->select();
		return $addressList ? $addressList : false;
	}
	
	/**
	 * 获取用户地址信息
	 * @param int $address_id 地址ID
	 */
	public static function get_address_info($address_id)
	{
		$address_db = D('user_address');
		$addressInfo = $address_db->find($address_id);
		return $addressInfo;
	}
	
	/**
	 * 添加/更新用户送货地址
	 * @param int $user_id 用户ID号
	 * @param array $post 表单
	 */
	public static function update_user_address($user_id, $post)
	{
		if(intval($user_id) ==0) return false;
		$post['delivery_cid'] = 44; //全部默认中国

		foreach ($post as $key => &$value) {
			$value = htmlspecialchars($value);
		}
		$address_id = isset($post['address_id']) ? intval($post['address_id']) : 0;
		$data = array(
			'user_id' => $user_id,
            'gendername' => isset($post['gendername']) ? trim($post['gendername']) : "男",
			'delivery_first_name' => trim($post['delivery_first_name']),
			'delivery_last_name' => trim($post['delivery_last_name']),
			'delivery_phone' => isset($post['delivery_phone']) ? trim($post['delivery_phone']) : null,
			'delivery_mobile' => isset($post['delivery_mobile']) ? trim($post['delivery_mobile']) : null,
			'delivery_postcode' => isset($post['delivery_postcode']) ? trim($post['delivery_postcode']) : 0,
			'delivery_email' => isset($post['delivery_email']) ? trim($post['delivery_email']) : null,
			'delivery_cid' => isset($post['delivery_cid']) ? intval($post['delivery_cid']) : 0,
			'delivery_pid' => isset($post['delivery_pid']) ? intval($post['delivery_pid']) : 0,
			'delivery_province' => isset($post['delivery_province']) ? trim($post['delivery_province']) : null,
			'delivery_city' => isset($post['delivery_city']) ? trim($post['delivery_city']) : null,
			'delivery_address' => isset($post['delivery_address']) ? trim($post['delivery_address']) : null,
			'delivery_address2' => isset($post['delivery_address2']) ? trim($post['delivery_address2']) : null,
			'delivery_address3' => isset($post['delivery_address3']) ? trim($post['delivery_address3']) : null,
			'start_time' => time(),
		);
		if(isset($post['default'])){
			$data['default'] = 1;
		}

		//更新国家
  	if($post['delivery_cid']){
  		$area_info = SiteModel::get_region_info($post['delivery_cid']);
  		if($area_info){
  			$data['delivery_country'] = $area_info['name'];
  		}
  	}
  	//更新省市
  	if($post['delivery_pid']){
  		$area_info = SiteModel::get_region_info($post['delivery_pid']);
  		if($area_info){
  			$data['delivery_province'] = $area_info['name'];
  		}
  	}
		$address_db = D('user_address');
		$count = $address_db->where(array('user_id' => $user_id))->count();
		if(!$count){
			$data['default'] = 1;
		}
		if(!$address_id){
			$affected = $address_id = $address_db->add($data);
		}else{
			$affected = $address_db->where('id='.$address_id)->save($data);
		}

		//设置其他不为默认
		if($data['default']){
			$set = array(
				'user_id' => $user_id,
				'id' => array('neq', $address_id),
			);
			$address_db->where($set)->save(array('default' => 0));
		}
		
		return $affected;
	}
	
	/**
	 * 检验是否存在相同的地址
	 * @param int $user_id 用户ID号
	 * @param string $delivery_address 详细地址
	 */
	public static function validate_address($user_id, $delivery_address)
	{
		$address_db = D('user_address');
		$where = array(
			'user_id' => $user_id,
			'delivery_address' => isset($delivery_address) ? trim($delivery_address) : null,
		);
		$count = $address_db->where($where)->count();
		return (boolean) $count;
	}

/**
 * 帐户变动
 * @param   int     $user_id        用户id
 * @param   float   $amount         变动金额
 * @param   int     $process_type   充值类型
 * @param   int     $is_paid        支付类型
 * @param   int     $paid_time      支付时间
 * @param   int     $admin_note     提示
 * @param   string  $user_note      提示
 * @return  bool
 */
   public static function user_account_change($user_id, $amount, $process_type, $is_paid = 1, $paid_time = NULL, $admin_note = NULL, $user_note = NULL){
   	    
   	    if($paid_time == NULL){
   	    	$paid_time = time();
   	    }   	    
   	    $amount_db = M('user_account');//充值日志
        $user_amount_data['user_id']   =  $user_id;
        $user_amount_data['add_time']  = time();
        $user_amount_data['paid_time'] = $paid_time;
        $user_amount_data['amount']    = $amount;
        $user_amount_data['process_type'] = $process_type; //类型为充值
        $user_amount_data['is_paid']      = $is_paid; //已完成支付
        if($admin_note) 
        	$user_amount_data['admin_note'] = $admin_note;        
        if($user_note) 
            $user_amount_data['user_note']  = $user_note;

        return $amount_db->add($user_amount_data);
   }	

	/**
 * 记录帐户变动
 * @param   int     $user_id        用户id
 * @param   float   $user_money     可用余额变动
 * @param   float   $frozen_money   冻结余额变动
 * @param   int     $rank_points    等级积分变动
 * @param   int     $pay_points     消费积分变动
 * @param   string  $change_desc    变动说明
 * @param   int     $change_type    变动类型：参见常量
 * @return  void
 */
	public static function log_account_change($user_id, $user_money = 0, $frozen_money = 0, $rank_points = 0, $pay_points = 0, $change_desc = '', $change_type = self::ACT_OTHER)
	{
		if(!intval($user_id))return false;
		$userInfo = self::get_user_info($user_id);
		if(!$userInfo) return false;
		
		/* 插入帐户变动记录 */
		$account_log = array(
			'user_id'       => $user_id,
			'user_money'    => $user_money,
			'frozen_money'  => $frozen_money,
			'rank_points'   => $rank_points,
			'pay_points'    => $pay_points,
			'change_time'   => time(),
			'change_desc'   => $change_desc,
			'change_type'   => $change_type
		);
		$user_account_db = D('user_account_log');
		$user_account_db->add($account_log);

		/* 更新用户信息 */
		$sql = "UPDATE __TABLE__ ".
				" SET `user_money` = `user_money` + ('$user_money')," .
				" `frozen_money` = `frozen_money` + ('$frozen_money')," .
				" `rank_points` = `rank_points` + ('$rank_points')," .
				" `pay_points` = `pay_points` + ('$pay_points')" .
				" WHERE `id` = '$user_id'";
		$user_db = D('users');
		$user_db->query($sql);
		
		//更新会员等级
		$userInfo = self::get_user_info($user_id);
		self::update_user_rank($user_id, $userInfo['rank_points']);
	}
	
	/**
	 * 会员可以最多使用多少积分支付
	 * @param float $product_amount 商品总价
	 * @return array
	 */
	public static function get_user_integral($product_amount)
	{
		global $user;
		if(isset($user['id']) && $user['id'] && floatval($user['pay_points']) > 0 && C('is_use_integral'))
		{
			$integral_scale = intval(C('integral_scale'));//积分换算比例
			$integral_percent = intval(C('integral_percent'));//积分支付比例
			if( $integral_scale == 0 || $integral_percent == 0) return false;
			//最多使用积分数
			$total_integral = $product_amount*$integral_percent/$integral_scale;
			//可用积分
			if(floatval($user['pay_points'])<$total_integral)
				$total_integral = floatval($user['pay_points']);
			//可抵消的价格
			$integral_money = $total_integral*$integral_scale/100;
			return array($total_integral, $integral_money);
		}
		return false;
	}
	
	/**
	 * 获取邮件模板信息
	 * @param string $path_alias 别名
	 * @param int $language_id 语言
	 */
	public static function get_email_template_info($path_alias, $language_id=0)
	{
		if(!intval($language_id)){
			$language_id = C('language_id');
		}
		$where = array(
			'path_alias' => $path_alias,
			'language_id' => $language_id,
		);
		$email_db = D('email_template_items');
		$email_db->field('title,content');
		$email_db->join('email_template ON email_template.id = email_template_items.email_template_id');
		$result = $email_db->where($where)->find();
		if(!$result){
			$where = array(
				'path_alias' => $path_alias,
				'language_id' => C('language_id'),
			);
			$email_db = D('email_template_items');
			$email_db->field('title,content');
			$email_db->join('email_template ON email_template.id = email_template_items.email_template_id');
			$result = $email_db->where($where)->find();
		}
		return $result;
	}
	
	/**
	 * 获取订阅邮箱
	 * @param string $email
	 */
	public static function get_email_registory_info($email)
	{
		$email_registry = D('email_registry');
		$res = $email_registry->where(array('email' => $email))->find();
		return $res;
	}
	
	/**
	 * 更新订阅
	 * @param string $email
	 * @param int $status
	 */
	public static function update_email_registory($email, $status = 1)
	{
		$status = !isset($status) ? 1 : $status;
		$email_registry = D('email_registry');
		$emailInfo = self::get_email_registory_info($email);
		if(!$emailInfo){
			$data = array(
				'email' => $email,
				'status' => 1,
			);
			$email_registry->add($data);
		}elseif($emailInfo && $emailInfo['status'] != $status){
			$email_registry->where('id='.$emailInfo['id'])->save(array('status' => $status));
		}
	}
	
	/**
	 * 获取设计师信息
	 * @param int $designer_id
	 */
	public static function get_user_designer_info($designer_id)
	{
		$user_designer_db = D('user_designer');
		$designer = $user_designer_db->where('user_id='.$designer_id)->find();
		return $designer;
	}
	
	/**
	 * 获取购买商品的列表
	 */
	public static function get_product_list($pid)
	{
		global $user;
		$sd_db = D('shaidan');
		$sdList = $sd_db->field('product_id')->where('user_id='.$user['id'].'')->order('id DESC')->select();
		foreach ($sdList as $s){
				$sid[] = $s['product_id'];
		}
		
		
		$MyProductList = array();
		$order_db = D('orders');
		$ordersList = $order_db->field('id')->where('order_status=2 AND user_id='.$user['id'].'')->order('id DESC')->select();
		foreach ($ordersList as $v){
			$MyProduct = OrderModel::get_order_product_list($v['id']);
			for($i=0;$i<count($MyProduct);$i++){
				$v['id'] = $MyProduct[$i]['product_id'];
				if (in_array($v['id'],$sid))
				{
					continue;
				}
				else
				{
					$MyProductList[$v['id']]['pid'] = $pid;
					$MyProductList[$v['id']]['id'] = $v['id'];
					$MyProductList[$v['id']]['product_name'] = $MyProduct[$i]['product_name'];
				}
			}
			
		}
		return $MyProductList;
	}
	
	/**
	 * 查看用户有多少个红包使用
	 */
	public static function get_bonus_list()
	{
		global $user;
		
		$where = array(
			'user_bonus.user_id' => $user['id'],
			'user_bonus.used_time' => 0,
			
		);
		$bonus_db = D('user_bonus');
		$bonus_db->field('user_bonus.id,bonus_type.type_name,bonus_type.type_money,bonus_type.restrict,bonus_type.use_start_date,bonus_type.use_end_date,bonus_type.min_goods_amount');
		$bonus_db->join('bonus_type ON bonus_type.id = user_bonus.bonus_id');
		$bonusList = $bonus_db->where($where)->select();
		$bonusList02 = array();
		$i = 0;
		foreach ($bonusList as $v){
			if($v['restrict'] == 0){
				if(time() >= $v['use_start_date'] && time() <= $v['use_end_date']){
					$bonusList02[$i]['id'] 				= $v['id'];
					$bonusList02[$i]['type_name'] 		= $v['type_name'];
					$bonusList02[$i]['type_money'] 		= $v['type_money'];
					$bonusList02[$i]['min_goods_amount'] 		= $v['min_goods_amount'];
				}
			}else{
				$bonusList02[$i]['id'] 				= $v['id'];
				$bonusList02[$i]['type_name'] 		= $v['type_name'];
				$bonusList02[$i]['type_money'] 		= $v['type_money'];
				$bonusList02[$i]['min_goods_amount'] 		= $v['min_goods_amount'];
			}
			
			if($bonusList02[$i]){
			    $fortunewheel = D('fortunewheel')->field('is_share')->where(array('user_id'=>$user['id'], 'prize_content'=>$v['type_name']))->find();
				if(!$fortunewheel || $fortunewheel['is_share']==1){
				    $bonusList02[$i]['is_share'] = 1;
				}else{
				    $bonusList02[$i]['is_share'] = 0; 
				} 	
			}
			
			$i++;
		}
		return $bonusList02;
	}
	
	/**
	 * 查看用户红包的金额
	 */
	public static function get_bonus_info($id)
	{
		global $user;
		
		$where = array(
			'user_bonus.id' => $id,
		);
		$bonus_db = D('user_bonus');
		$bonus_db->field('user_bonus.id,bonus_type.type_name,bonus_type.type_money');
		$bonus_db->join('bonus_type ON bonus_type.id = user_bonus.bonus_id');
		$bonusInfo = $bonus_db->where($where)->find();
		
		return $bonusInfo;
	}
	public static function user_bonus($name,$user_id=0){
		$bonus_type = D("bonus_type");
		$where = array(
			'type_name'  => $name,
		);
		$bonus_type_info =$bonus_type->where($where)->find();
		$user_bonus = D('user_bonus');
		//$set['used_time'] = time();
		$set['time'] = time();
		$set['bonus_sn'] = 0;
		$set['user_id'] = $user_id;
		$set['bonus_id'] =$bonus_type_info['id']; 
		$bonus_info =$user_bonus->add($set);
		return $bonus_info;
	}

	/**
	 * 自动把合作伙伴下面的客户新增成网站会员
	 */
	public static function partner_user_add($address_id)
	{
		$address_db = D('user_address');
		$address = $address_db->find($address_id);
		if (!$address)
		{
			return false;
		}
		$post['username'] = $address['delivery_phone'];
		//$post['email']    = $address['delivery_email'];	
		$post['password'] = $address['delivery_phone'];	
		
		import("COM.Validate");
		//验证手机号 是否唯一
		if (empty($post['username']) || !Validate::registerPhone($post['username'])
		    || self::validate_username_only($post['username']))
		{
			return false;
		}
		// //验证邮箱 是否唯一
		// if (empty($post['email']) || !Validate::email($post['email'])
		//    || self::validate_email_only($post['email']))
		// {
		// 	return false;
		// }

		if(preg_match("/^1(3[4-9]|47|5[012789]|8[2378])\d{8}$/",$post['username'])){//移动
			$post['email'] = $post['username']."@139.com";
		}else if(preg_match("/^1(3[0-2]|45|5[56]|8[56])\d{8}$/",$post['username'])){//联通
			$post['email'] = $post['username']."@wo.com.cn";
		}else {//电信
			$post['email'] = $post['username']."@189.cn";
		}		
        
        $post['first_name'] = $address['delivery_first_name'];
		//加入会员
		if (!$user_id = self::insert_user($post))
		{
            return false;
		}
		else
		{
            //注册通知短信
            $ShortMessage=A("ShortMessage");
            $str_short_message='{"username":"'.$post['username'].'","password":"'.$post['password'].'","ownonly":"ownonly.net"}';
            $short_mesg_result=$ShortMessage->send_message("SMS_4740514",$post['username'],$str_short_message);
            if($short_mesg_result){
                Log::write('注册短信，邮箱：'.$post['email'].'，时间：'.date("Y-m-d H:i:s",time()));
            }
			//拷贝用户地址
			unset($address['id']);
			$address['delivery_email'] = $post['email'];
		    self::update_user_address($user_id, $address);
			//拷贝用户身型
	        $measure = MeasureModel::get_measure_one(array('address_id'=>$address_id));
	        $measure['user_id'] = $user_id;
	        $measure['measure_name'] = $address['delivery_first_name'];
	        unset($measure['id']);
	        unset($measure['address_id']);
            D('user_measure')->add($measure);
    
			return true;
		}       
	}
    //推荐好友返现
     public function get_money_friend($coupon="",$username=""){
         if($coupon||$username) {
             //判断优惠码是否是朋友推荐所得
             if($coupon){
                 $where['invite_coupon_code']=$coupon;
                 $where['use_status']=0;
             }
             if($username){
                 $where['user_mobile']=$username;
                 $where['use_status']=2;
             }
             if ($invite_info=D("refe_invite_items")->where($where)->find()){
                 //判断用户是否存在
                    $user=D("users")->where(array('username'=>$invite_info['user_mobile']))->find();
                     if($user) {
                         //给推荐充值一百元余额
                         D("users")->query("update __TABLE__ set user_money=user_money+100 where username=" . $invite_info['user_mobile']);
                         //写入日志
                         $setsql['user_id'] = $user['id'];
                         $setsql['user_money'] = 100;
                         $setsql['change_time'] = time();
                         $setsql['change_desc'] = "被邀请朋友订单满300返余额100";
                         $setsql['change_type'] = 5;
                         $setsql2['user_id'] = $user['id'];
                         $setsql2['amount'] = 100;
                         $setsql2['add_time'] = time();
                         $setsql2['paid_time'] = time();
                         $setsql2['user_account'] = "被邀请朋友订单满300返余额100";
                         $setsql2['is_paid'] = 1;
                        if (D("user_account_log")->add($setsql) && D("user_account")->add($setsql2)) {
                             D('refe_invite_items')->where("id=" . $invite_info['id'])->save(array('use_status' => 1));
                         }
                     }else{
                         D('refe_invite_items')->where("id=" . $invite_info['id'])->save(array('use_status' => 2));
                     }
             }
         }
     }
}